<template>
	<view class="water-cart">
		<!-- 购物车底部栏 - 一直显示 -->
		<view class="cart-bar">
			<!-- 购物车图标和数量 -->
			<view class="cart-icon-wrapper" @click="toggleCart">
				<!-- 使用徽标包装购物车图标 -->
				<wd-badge v-if="cartData.goodsNum > 0" :model-value="cartData.goodsNum > 99 ? '99+' : cartData.goodsNum">
					<image 
						src="/pagesA/static/cat_img.png" 
						class="cart-icon" 
						mode="aspectFit"
					/>
				</wd-badge>
				<!-- 没有商品时只显示购物车图标 -->
				<image 
					v-else
					src="/pagesA/static/cat_img.png" 
					class="cart-icon" 
					mode="aspectFit"
				/>
			</view>
			
			<!-- 价格信息 -->
			<view class="price-info">
				<view class="total-price">
					<text class="price-symbol">¥</text>
					<text class="price-value">{{ cartData.totalAmount || 0  }}</text>
				</view>
				<text class="discount-text">已享受更低优惠</text>
			</view>
			
			<!-- 结算按钮 -->
			<view 
				class="checkout-btn" 
				:class="{ 'disabled': cartData.goodsNum === 0 || selectedCount === 0 }"
				@click="handleCheckout"
			>
				<text class="checkout-text">去结算</text>
			</view>
		</view>
		
		<!-- 购物车弹窗 -->
		<wd-popup 
			v-model="showCart" 
			position="bottom" 
			:z-index="999"
			:close-on-click-modal="true"
			:round="true"
		>
			<view class="cart-popup">
				<!-- 弹窗头部 -->
				<view class="popup-header">
					<view class="header-left">
						<wd-checkbox 
							v-model="selectAllValue" 
							@change="handleSelectAllChange"
							checked-color="#333"
							size="large"
						>
							已选购商品（{{cartData.goodsNum}}件）
						</wd-checkbox>
					</view>
					<view 
						class="clear-cart" 
						@click="clearCart"
					>
						<wd-icon name="delete" size="16px" color="#999" />
						<text class="clear-text">清空购物车</text>
					</view>
				</view>
				
				<!-- 购物车内容 -->
				<view class="cart-content">
					<!-- 商品列表 -->
					<scroll-view 
						class="cart-list" 
						scroll-y 
						:style="{ height: scrollHeight + 'px' }"
					>
						<view 
							v-for="(item, index) in cartData.detailList" 
							:key="item.id" 
							class="cart-item"
						>
							<!-- 复选框 -->
							<view class="item-checkbox">
								<wd-checkbox 
									v-model="item.isSelect" 
									@change="handleItemChange(index, $event)"
									checked-color="#333"
									size="large"
								/>
							</view>
							
							<!-- 商品图片 -->
							<image 
								:src="item.cover || '/static/img/bg1.png'" 
								class="item-image" 
								mode="aspectFill"
							/>
							
							<!-- 商品信息 -->
							<view class="item-info">
								<text class="item-name">{{ item.goodsName || item.name || '' }}</text>
								<text class="item-desc">{{ item.goodsDetail || item.desc || '' }}</text>
								
								<!-- 价格和数量控制 -->
								<view class="item-bottom">
									<view class="item-price">
										<text class="price-symbol">¥</text>
										<text class="price-value">{{ item.price || 0 }}</text>
									</view>
									
									<!-- 数量控制器 -->
									<view class="quantity-controls">
										<view 
											class="control-btn minus-btn"
											@click="changeQuantity(1,item, index)"
										>
											<wd-icon name="decrease" color="#fff" size="13px"></wd-icon>
										</view>
										<text class="quantity-text">{{ item.count || item.quantity || 0 }}</text>
										<view 
											class="control-btn plus-btn"
											@click="changeQuantity(0,item, index)"
										>
											<wd-icon name="add" color="#fff" size="13px"></wd-icon>
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				
				<!-- 弹窗底部结算 -->
				<view  class="popup-footer">
					<view class="footer-price">
						<text class="total-label">预计到手</text>
						<text class="price-symbol">¥</text>
						<text class="total-amount">{{ cartData.totalAmount || 0  }}</text>
					</view>
					<view 
						class="footer-checkout-btn" 
						:class="{ 'disabled': selectedCount === 0 }"
						@click="handleCheckout"
					>
						<text class="checkout-text">去结算</text>
					</view>
				</view>
			</view>
		</wd-popup>
	</view>
</template>

<script setup>
	import { ref, computed, watch } from 'vue'
	
	/**
	 * 组件属性定义
	 */
	const props = defineProps({
		// 购物车数据
		cartData: {
			type: Object,
			default: () => ({
				detailList: [],
				goodsNum: 0, // 总数量
				totalAmount: 0 ,// 总价格
				venueId: null ,// 商家ID
				venueName: null // 商家名称
			})
		},
		// 滚动区域最大高度
		maxScrollHeight: {
			type: Number,
			default: 400
		}
	})

	/**
	 * 事件定义
	 */
	const emit = defineEmits([
		'update-cart',    // 更新购物车
		'checkout',       // 结算
		'item-change'     // 商品数量变化
	])

	/**
	 * 响应式数据
	 */
	const showCart = ref(false) // 是否显示购物车弹窗
	const selectAllValue = ref(true) // 全选状态，默认全选

	/**
	 * 计算属性
	 */
	// 滚动区域高度
	const scrollHeight = computed(() => {
		const itemHeight = 120 // 每个商品项的高度
		const maxItems = Math.floor(props.maxScrollHeight / itemHeight)
		const actualItems = props.cartData?.detailList?.length
		return Math.min(actualItems * itemHeight, props.maxScrollHeight)
	})
	
	// 已选商品数量
	const selectedCount = computed(() => {
		if (!props.cartData.detailList) return 0
		return props.cartData.detailList.filter(item => item.isSelect === true).length
	})
	
	// 已选商品总价
	const selectedTotalPrice = computed(() => {
		if (!props.cartData.detailList) return 0
		return props.cartData.detailList
			.filter(item => item.isSelect === true)
			.reduce((total, item) => total + (item.price || 0) * (item.count || item.quantity || 0), 0)
	})

	/**
	 * 监听购物车数据变化
	 */
	watch(() => props.cartData, (newCartData) => {
		console.log('购物车数据更新:', newCartData)
		// 确保新商品默认选中
		if (newCartData.detailList && newCartData.detailList.length > 0) {
			// isSelect 是默认选中状态，true表示选中，1表示未选中
			// 更新全选状态
			selectAllValue.value = newCartData.detailList.every(item => item.isSelect)
		} else {
			selectAllValue.value = true
		}
	}, { deep: true })



	/**
	 * 格式化价格显示
	 * @param {number} price - 价格
	 * @returns {string} 格式化后的价格
	 */
	const formatPrice = (price) => {
		return (price || 0).toFixed(2)
	}

	/**
	 * 切换购物车显示状态
	 */
	const toggleCart = () => {
		// 没有商品时不能打开购物车弹窗
		if (props.cartData.goodsNum === 0) {
			uni.showToast({
				title: '购物车为空',
				icon: 'none'
			})
			return
		}
		showCart.value = !showCart.value
	}
	
	/**
	 * 处理全选状态变化
	 */
	const handleSelectAllChange = async (value) => {
		const updatedItems = [...props.cartData.detailList];
		if(value.value){//全选
		    // 0=选中；1=取消选中；2=取消全部选中 3=全部选中
		  let res = await uni.api.optSelect({
			 optType:3,
			 venueId:props.cartData.venueId
		 })
		 if(res.code==0){
			const updatedCart = {
				...res.data,
				venueId:props.cartData.venueId,
			}
			selectAllValue.value = updatedItems.every(item => item.isSelect === true)
			emit('update-cart', updatedCart)
		 }
		}else{//取消全选
			 let res = await uni.api.optSelect({
				 optType:2,
				 venueId:props.cartData.venueId
			})
			if(res.code==0){
				const updatedCart = {
					...res.data,
					venueId:props.cartData.venueId,
				}
				selectAllValue.value = updatedItems.every(item => item.isSelect === true)
				emit('update-cart', updatedCart)
			}
		}
	}
	
	/**
	 * 处理单个商品选择状态变化
	 * @param {number} index - 商品索引
	 * @param {boolean} value - 选择状态
	 */
	const handleItemChange = async (index, value) => {
		const updatedItems = [...props.cartData.detailList];
		// 0=选中；1=取消选中；
		if(value.value){//选中
		  let res = await uni.api.optSelect({
			 id:updatedItems[index].id,
			 optType:0,
			 venueId:props.cartData.venueId
		 })
		 if(res.code==0){
			const updatedCart = {
				...res.data,
				venueId:props.cartData.venueId,
			}
			selectAllValue.value = updatedItems.every(item => item.isSelect === true)
			emit('update-cart', updatedCart)
		 }
		}else{//取消全选
			 let res = await uni.api.optSelect({
				 id:updatedItems[index].id,
				 optType:1,
				 venueId:props.cartData.venueId
			})
			if(res.code==0){
				const updatedCart = {
					...res.data,
					venueId:props.cartData.venueId,
				}
				selectAllValue.value = updatedItems.every(item => item.isSelect === true)
				emit('update-cart', updatedCart)
			}
		}
	}
	/**
	 * 操作商品数量
	 * @param {Object} item - 商品项
	 * @param {number} index - 商品索引
	 */
	const changeQuantity = (type, item, index) => {
		 uni.api.optCarInfo({
			 godosId: item.goodsId,
			 goodsDetail: item.goodsDetail,
			 optType: type, //0=添加；1=减少；2=删除；
			 venueId: props.cartData.venueId
		 }).then(res => {
			 uni.$emit('refreshWaterBarData');
		 })
	}

	/**
	 * 清空购物车
	 */
	const clearCart = () => {
		uni.showModal({
			title: '提示',
			content: '确定要清空购物车吗？',
			success: (res) => {
				if (res.confirm) {
					 uni.api.cleanCar({
						 businessId:props.cartData.venueId
					}).then(res => {
						if(res.code==0){
							// 发送事件通知index页面刷新数据
							uni.$emit('refreshWaterBarData');
							uni.showToast({
								title: '购物车已清空',
								icon: 'none'
							})
							// 关闭弹窗
							showCart.value = false
						}	
					})
				
				}
			}
		})
	}

	/**
	 * 处理结算
	 */
	const handleCheckout = () => {
		// 检查是否有选中的商品
		if (selectedCount.value === 0) {
			uni.showToast({
				title: '请选择要结算的商品',
				icon: 'none'
			})
			return
		}
		
		// 获取已选中的商品
		const selectedItems = props.cartData.detailList.filter(item => item.isSelect === true)
		
		// 再次确认有选中的商品
		if (selectedItems.length === 0) {
			uni.showToast({
				title: '请选择要结算的商品',
				icon: 'none'
			})
			return
		}
		
		// 关闭弹窗
		showCart.value = false
		
		// 跳转到订单确认页面
		uni.navigateTo({
			url: `/pagesA/view/waterBar/orderConfirm?businessId=${props.cartData.venueId}&venueName=${props.cartData.venueName}`
		})
		
		// 触发结算事件，只传递已选中的商品
		emit('checkout', {
		})
	}

	/**
	 * 暴露给父组件的方法
	 */
	defineExpose({
		toggleCart,
		clearCart,
		showCart: () => showCart.value = true,
		hideCart: () => showCart.value = false
	})
</script>
<style scoped lang="scss">
	.water-cart {
		position: relative;
	}

	/* 购物车底部栏样式 */
	.cart-bar {
		position: fixed;
		bottom: 30rpx;
		left: 32rpx;
		right: 0;
		height: 96rpx;
		width: 691rpx;
		box-sizing: border-box;
		background: #ffffff;
		border-radius: 50rpx;
		box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.15);
		display: flex;
		align-items: center;
		padding: 0 0 0 28rpx;
		z-index: 888;
		
		.cart-icon-wrapper {
			position: relative;
			margin-right: 24rpx;
			
			.cart-icon {
				width: 60rpx;
				height: 60rpx;
			}
		}
		
		.price-info {
			flex: 1;
			color: #333;
			height: 100%;
			position: relative;
			margin-left: 20rpx;
			.total-price {
				flex: 1;
				display: flex;
				align-items: baseline;
				margin-bottom: 4rpx;
				
				.price-symbol {
					font-size: 36rpx;
					margin-right: 4rpx;
				}
				
				.price-value {
					font-size: 36rpx;
					font-weight: bold;
				}
			}
			
			.discount-text {
				font-size: 22rpx;
				color: #999;
				position: absolute;
				bottom: 16rpx;
			}
		}
		
		.checkout-btn {
			background: #000000;
			border-radius: 56rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 160rpx;
			
			&.disabled {
				background: #ccc;
			}
			
			.checkout-text {
				color: #fff;
				font-size: 28rpx;
				font-weight: bold;
			}
		}
	}

	/* 购物车弹窗样式 */
	.cart-popup {
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		max-height: 80vh;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		
		.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1px solid #f0f0f0;
		
		.header-left {
			display: flex;
			align-items: center;
		}
			
			.clear-cart {
				display: flex;
				align-items: center;
				
				.clear-text {
					font-size: 24rpx;
					color: #999;
					margin-left: 8rpx;
				}
			}
		}
		
		.cart-content {
			flex: 1;
			min-height: 400rpx;
			width: 100%;
			box-sizing: border-box;
			overflow: hidden;
			
			.empty-cart {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 80rpx 0;
				
				.empty-image {
					width: 200rpx;
					height: 200rpx;
					margin-bottom: 24rpx;
				}
				
				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}
			
			.cart-list {
				padding: 0 32rpx;
				width: 100%;
				box-sizing: border-box;
				
				.cart-item {
					display: flex;
					align-items: center;
					padding: 24rpx 0;
					border-bottom: 1px solid #f0f0f0;
					width: 100%;
					box-sizing: border-box;
					
					
					&:last-child {
						border-bottom: none;
					}
					
					.item-image {
						width: 120rpx;
						height: 120rpx;
						border-radius: 12rpx;
						margin-right: 24rpx;
						flex-shrink: 0;
					}
					
					.item-info {
						flex: 1;
						min-width: 0;
						width: 0;
						
						.item-name {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
							display: block;
							margin-bottom: 8rpx;
							word-wrap: break-word;
							word-break: break-all;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
						}
						
						.item-desc {
							font-size: 24rpx;
							color: #999;
							display: block;
							margin-bottom: 16rpx;
							word-wrap: break-word;
							word-break: break-all;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 1;
							-webkit-box-orient: vertical;
						}
						
						.item-bottom {
							display: flex;
							align-items: center;
							justify-content: space-between;
							
							.item-price {
								display: flex;
								align-items: baseline;
								color: #606266;
								font-weight: bold;
								
								.price-symbol {
									font-size: 20rpx;
									margin-right: 4rpx;
								}
								
								.price-value {
									font-size: 28rpx;
								}
							}
							
							.quantity-controls {
								display: flex;
								align-items: center;
								.control-btn {
									width: 42rpx;
									height: 42rpx;
									border-radius: 50%;
									display: flex;
									align-items: center;
									justify-content: center;
									
									&.minus-btn {
										background: #333;
									}
									
									&.plus-btn {
										background: #333;
									}
								}
								
								.quantity-text {
									font-size: 28rpx;
									color: #333;
									margin: 0 24rpx;
									min-width: 40rpx;
									text-align: center;
								}
							}
						}
					}
				}
			}
		}
		
		.popup-footer {
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-top: 1px solid #f0f0f0;
			background: #fff;
			min-height: 96rpx;
			box-sizing: border-box;
			padding: 0 28rpx;
			padding-top: 12rpx;
			/* 可以通过增加padding-bottom来适配 */  
			padding-bottom: constant(safe-area-inset-bottom); /*兼容 IOS<11.2*/  
			padding-bottom: env(safe-area-inset-bottom); /*兼容 IOS>11.2*/
			.footer-price {
				display: flex;
				align-items: baseline;
				
				.total-label {
					font-size: 28rpx;
					color: #333;
					margin-right: 8rpx;
				}
				
				.price-symbol {
					font-size: 28rpx;
					margin-right: 4rpx;
				}
				
				.total-amount {
					font-size: 34rpx;
				}
			}
			
			.footer-checkout-btn {
				background: #000;
				border-radius: 56rpx;
				min-height: 96rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 160rpx;
				
				&.disabled {
					background: #ccc;
				}
				
				.checkout-text {
					color: #fff;
					font-size: 28rpx;
					font-weight: bold;
				}
			}
		}
	}
</style>
	
